package cn.shenshen.shop.service.impl;

import cn.shenshen.shop.domain.OrderInfo;
import cn.shenshen.shop.domain.SeckillOrder;
import cn.shenshen.shop.mapper.OrderInfoMapper;
import cn.shenshen.shop.service.IOrderInfoService;
import cn.shenshen.shop.service.ISeckillGoodService;
import cn.shenshen.shop.service.ISeckillOrderService;
import cn.shenshen.shop.util.IdGenerateUtil;
import cn.shenshen.shop.vo.GoodVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderInfoServiceImpl implements IOrderInfoService {

    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Transactional//事务
    public String doSeckill(Long userId, Long goodId) {
        //扣减库存
        int count = seckillGoodService.descStock(goodId);
        //创建订单
        OrderInfo orderInfo = createOrderInfo(userId,goodId);
        //创建秒杀订单
        seckillOrderService.createSeckillOrder(userId,goodId,orderInfo.getOrderNo());

        return orderInfo.getOrderNo();
    }

    public OrderInfo createOrderInfo(Long userId, Long goodId) {
        //查询商品信息
        GoodVo goodVo = seckillGoodService.find(goodId);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(IdGenerateUtil.get().nextId()+"");
        orderInfo.setSeckillPrice(goodVo.getSeckillPrice());
        orderInfo.setGoodImg(goodVo.getGoodImg());
        orderInfo.setGoodId(goodId);
        orderInfo.setGoodCount(1);
        orderInfo.setDeliveryAddrId(null);
        orderInfo.setGoodName(goodVo.getGoodName());
        orderInfo.setCreateDate(new Date());
        orderInfo.setGoodPrice(goodVo.getGoodPrice());
        orderInfo.setUserId(userId);
        //保存到数据库
        orderInfoMapper.insert(orderInfo);
        return orderInfo;
    }

    public OrderInfo find(String orderNo) {

        return orderInfoMapper.find(orderNo);
    }
}
